<!DOCTYPE html>
<html lang="en">

<head>
  <title>LineSegments2 高亮测试</title>
  <meta charset="utf-8" />
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script type="module">
    import * as THREE from 'https://cdn.skypack.dev/three'
    import { OrbitControls } from 'https://cdn.skypack.dev/three/examples/jsm/controls/OrbitControls'
    import { LineSegments2 } from 'https://cdn.skypack.dev/three/addons'
    import { LineSegmentsGeometry } from 'https://cdn.skypack.dev/three/addons'
    import { LineMaterial } from 'https://cdn.skypack.dev/three/addons'

    const scene = new THREE.Scene()
    const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
    camera.position.set(0, 0, 100)

    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)

    const controls = new OrbitControls(camera, renderer.domElement)

    // 创建 2 条线段
    const positions = [
      -10, 0, 0, 10, 0, 0,   // 第 0 条线段
      -10, 10, 0, 10, 10, 0   // 第 1 条线段
    ]

    const colors = [
      0, 1, 0, 0, 1, 0,      // green
      0, 0, 1, 0, 0, 1       // blue
    ]

    const geometry = new LineSegmentsGeometry()
    geometry.setPositions(positions)
    geometry.setAttribute('instanceColor', new THREE.InstancedBufferAttribute(new Float32Array(colors), 3))

    const material = new LineMaterial({
      linewidth: 5,
      vertexColors: true,
      color: 0xffffff,
      transparent: true,
      opacity: 1,
      resolution: new THREE.Vector2(window.innerWidth, window.innerHeight)
    })

    // 注入 shader 支持 instanceColor
    material.onBeforeCompile = shader => {
      shader.vertexShader = shader.vertexShader.replace(
        '#include <color_vertex>',
        `#ifdef USE_COLOR
            vColor.xyz = instanceColor.xyz;
          #endif`
      )
    }

    const lineSegments = new LineSegments2(geometry, material)
    scene.add(lineSegments)

    // 模拟高亮第 1 条线段（蓝色 → 黄色）
    setTimeout(() => {
      const attr = geometry.getAttribute('instanceColor')
      const highlightColor = new THREE.Color(0xffff00) // yellow
      attr.setXYZ(2, highlightColor.r, highlightColor.g, highlightColor.b) // 第 1 条线段点 A
      attr.setXYZ(3, highlightColor.r, highlightColor.g, highlightColor.b) // 第 1 条线段点 B
      attr.needsUpdate = true
        ('高亮完成')
    }, 2000)

    window.addEventListener('resize', () => {
      renderer.setSize(window.innerWidth, window.innerHeight)
      camera.aspect = window.innerWidth / window.innerHeight
      camera.updateProjectionMatrix()
      material.resolution.set(window.innerWidth, window.innerHeight)
    })

    function animate () {
      requestAnimationFrame(animate)
      renderer.render(scene, camera)
    }

    animate()
  </script>
</body>

</html>